package com.zxy.controlcenter.modular.system.controller;

import com.xiaoleilu.hutool.http.HttpUtil;
import com.zxy.controlcenter.core.log.LogManager;
import com.zxy.controlcenter.core.log.factory.LogTaskFactory;
import com.zxy.controlcenter.core.shiro.ShiroKit;
import com.zxy.controlcenter.core.shiro.ShiroUser;
import com.zxy.controlcenter.core.http.BaseController;
import com.zxy.controlcenter.modular.system.message.request.LoginRes;
import com.zxy.controlcenter.modular.system.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zxy
 */
@Slf4j
@Api(tags = "登录控制器")
@RestController
public class LoginController extends BaseController {

    private final AdminService adminService;

    public LoginController(AdminService adminService) {
        this.adminService = adminService;
    }

    @ApiOperation(value = "跳转到主页")
    @GetMapping(value = "/")
    public String index(Model model) {
        //获取当前用户角色列表
        ShiroUser user = ShiroKit.getUserNotNull();
        List<Long> roleList = user.getRoleList();
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            model.addAttribute("tips", "该用户没有角色，无法登陆");
            return "login";
        }
//        List<MenuNode> menus = userService.getUserMenuNodes(roleList);
//        model.addAttribute("menus", menus);
        return "index";
    }

    @ApiOperation(value = "登录接口")
    @PostMapping("/doLogin")
    public String doLogin(LoginRes loginRes, HttpServletRequest request) {
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginRes.getAccount(), loginRes.getPassword().toCharArray());

        //如果开启了记住我功能
        if ("on".equals(loginRes.getRememberMe())) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        //执行shiro登录操作
        currentUser.login(token);
        //登录成功，记录登录日志
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), HttpUtil.getClientIP(request)));

        ShiroKit.getSession().setAttribute("sessionFlag", true);
        return REDIRECT + "/";
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/login")
    public String login() {
        return "please login!";
    }
}
